<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编码" prop="itemCode">
        <el-input v-model="queryParams.itemCode" placeholder="请输入检验项目编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目名称" prop="itemName">
        <el-input v-model="queryParams.itemName" placeholder="请输入检验项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="标准编码" prop="standardCode">
        <el-input v-model="queryParams.standardCode" placeholder="请输入标准编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['quality:item:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['quality:item:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['quality:item:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['quality:item:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目ID" align="center" prop="itemId" />
      <el-table-column label="项目编码" align="center" prop="itemCode" />
      <el-table-column label="项目名称" align="center" prop="itemName" />
      <el-table-column label="标准编码" align="center" prop="standardCode" />
      <el-table-column label="检验方法" align="center" prop="inspectionMethod" />
      <el-table-column label="检验工具" align="center" prop="inspectionTool" />
      <el-table-column label="标准值" align="center" prop="standardValue" />
      <el-table-column label="上限值" align="center" prop="upperLimit" />
      <el-table-column label="下限值" align="center" prop="lowerLimit" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="是否必检" align="center" prop="isRequired">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isRequired" />
        </template>
      </el-table-column>
      <el-table-column label="序号" align="center" prop="sequence" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['quality:item:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['quality:item:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改质量检验项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目编码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入检验项目编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入检验项目名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="质量标准" prop="standardId">
              <el-select v-model="form.standardId" placeholder="请选择质量标准" clearable @change="handleStandardChange"
                style="width: 100%">
                <el-option v-for="standard in standardList" :key="standard.standardId"
                  :label="`${standard.standardCode} - ${standard.standardName}`" :value="standard.standardId">
                  <span style="float: left">{{ standard.standardCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ standard.standardName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 检验信息 -->
        <el-divider content-position="left">检验信息</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验方法" prop="inspectionMethod">
              <el-input v-model="form.inspectionMethod" placeholder="请输入检验方法" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验工具" prop="inspectionTool">
              <el-input v-model="form.inspectionTool" placeholder="请输入检验工具" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 标准值设置 -->
        <el-divider content-position="left">标准值设置</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标准值" prop="standardValue">
              <el-input v-model="form.standardValue" placeholder="请输入标准值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上限值" prop="upperLimit">
              <el-input v-model="form.upperLimit" placeholder="请输入上限值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限值" prop="lowerLimit">
              <el-input v-model="form.lowerLimit" placeholder="请输入下限值" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 其他设置 -->
        <el-divider content-position="left">其他设置</el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="sequence">
              <el-input v-model="form.sequence" placeholder="请输入序号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否必检" prop="isRequired">
              <el-radio-group v-model="form.isRequired">
                <el-radio v-for="dict in dict.type.sys_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItem, getItem, delItem, addItem, updateItem, checkItemCodeUnique } from "@/api/mes/quality/item";
import { listStandard } from "@/api/mes/quality/standard";

export default {
  name: "Item",
  dicts: ['sys_normal_disable', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 质量检验项目表格数据
      itemList: [],
      // 质量标准列表
      standardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        itemName: null,
        standardCode: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      // 在表单验证规则中添加
      rules: {
        itemCode: [
          { required: true, message: "检验项目编码不能为空", trigger: "blur" },
          { validator: this.validateItemCode, trigger: "blur" }
        ],
        itemName: [
          { required: true, message: "检验项目名称不能为空", trigger: "blur" }
        ],
        standardId: [
          { required: true, message: "请选择质量标准", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getStandardList();
  },
  methods: {
    /** 查询质量检验项目列表 */
    getList() {
      this.loading = true;
      listItem(this.queryParams).then(response => {
        this.itemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询质量标准列表 */
    getStandardList() {
      listStandard({ status: '0' }).then(response => {
        this.standardList = response.rows || [];
      });
    },
    /** 标准选择改变事件 */
    handleStandardChange(standardId) {
      if (standardId) {
        const selectedStandard = this.standardList.find(item => item.standardId === standardId);
        if (selectedStandard) {
          this.form.standardCode = selectedStandard.standardCode;
        }
      } else {
        this.form.standardCode = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: null,
        itemCode: null,
        itemName: null,
        standardId: null,
        standardCode: null,
        inspectionMethod: null,
        inspectionTool: null,
        standardValue: null,
        upperLimit: null,
        lowerLimit: null,
        unit: null,
        isRequired: "0",
        sequence: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getStandardList(); // 重新加载标准列表
      this.open = true;
      this.title = "添加质量检验项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getStandardList(); // 重新加载标准列表
      const itemId = row.itemId || this.ids
      getItem(itemId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改质量检验项目";
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加质量检验项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const itemId = row.itemId || this.ids
      getItem(itemId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改质量检验项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.itemId != null) {
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      this.$modal.confirm('是否确认删除质量检验项目编号为"' + itemIds + '"的数据项？').then(function () {
        return delItem(itemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('quality/item/export', {
        ...this.queryParams
      }, `item_${new Date().getTime()}.xlsx`)
    },
    /** 校验检验项目编码唯一性 */
    validateItemCode(rule, value, callback) {
      if (value) {
        checkItemCodeUnique(value).then(response => {
          if (response.data) {
            callback();
          } else {
            callback(new Error("检验项目编码已存在"));
          }
        });
      } else {
        callback();
      }
    }
  }
};
</script>